package com.thlws.java.proxy.dynamic_jdk;

import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;
import java.lang.reflect.Proxy;

/**
 * The type Jdk proxy.
 *
 * @param <T> the type parameter
 * @author HanleyTang
 * @date 2018 -12-04
 */
public class JDKProxy<T> implements InvocationHandler {

    //目标对象(被代理对象)
    private T target;


    public JDKProxy(T target) {
        this.target = target;
    }

    /**
     * Create proxy instance.
     *
     * @return 代理对象
     */
    public T createProxyInstance(){

        //三个参数含义
        //1.目标对象的ClassLoader;
        //2.目标对象的接口列表;
        //3.InvocationHandler 实例;
        return (T) Proxy.newProxyInstance(target.getClass().getClassLoader()
                , target.getClass().getInterfaces(), this);
    }

    @Override
    public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {

        System.out.println("proxy.getClass().getName() = " + proxy.getClass().getName());
        System.out.println("----before.invoke----");
        Object result = method.invoke(target, args);
        System.out.println("----after.invoke----");

        return result;
    }
}
